<template>
  <div class="container">
    <div class="content">
      <a-form @submit="Submit" :form="form">
        <div id="listDiv">
          <div class="listDiv" v-for="(item,index) in receiptList" :key="index">
            <div class="list_item">
              <a-row :gutter="8">
                <a-col :span="6">
                  <a-row>
                    <a-col :span="24">
                      <a-form-item
                        label="会员编号"
                        :label-col="{ span: 8}"
                        :wrapper-col="{ span: 15,offset:1 }"
                      >
                        <a-input
                          allowClear
                          type="number"
                          :maxLength="20"
                          @blur="memberNoBlur"
                          v-decorator="[
                                                                `memberNo[${index}]`,
                                                                {rules: [{ required: true, message: '请输入会员编号'},{validator: validatMemberNo}]}
                                                          ]"
                          placeholder="请输入20位数字"
                        ></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :span="24">
                      <a-form-item
                        :label-col="{ span: 8}"
                        :wrapper-col="{ span: 15,offset:1 }"
                        label="分账比例"
                      >
                        <a-input
                          v-decorator="[
                        `ratio[${index}]`,
                        {rules: [{ required: true, message: '请输入分账比例'},{validator: validatRatio}],validateTrigger: 'blur'}
                  ]"
                        >
                          <span slot="addonAfter">%</span>
                        </a-input>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-col>
                <a-col :span="7">
                  <a-form-item
                    :label-col="{ span: 6}"
                    :wrapper-col="{ span: 17,offset:1 }"
                    label="客户全称："
                  >
                    <span>{{item.memberName}}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="9">
                  <a-form-item
                    v-bind="formItemLayout"
                    label="上传协议"
                    :help="`仅支持图片格式JPG、PNG，且每个文件大小不超过${imageSize}M`"
                  >
                    <div class="clearfix" @click="clickUpload(index)">
                      <a-upload
                        v-decorator="[`uploadList[${index}]`, {rules: [{ required: true, message: '请上传协议'}]}]"
                        name="upfile"
                        :headers="henderstoken"
                        action="/file/file/upload"
                        listType="picture-card"
                        :fileList="item.fileList"
                        :data="{to}"
                        @preview="handlePreview"
                        @change="handleChange"
                      >
                        <div v-if="item.fileList.length < 1">
                          <a-icon type="plus" />
                          <div class="ant-upload-text">双方合作协议</div>
                        </div>
                      </a-upload>
                      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                        <img alt="example" style="width: 100%" :src="previewImage" />
                      </a-modal>
                    </div>
                  </a-form-item>
                </a-col>
                <a-col style="height: 100%;" :span="2">
                  <div class="action">
                    <a-button @click="deleteItem(index)">删除</a-button>
                  </div>
                </a-col>
              </a-row>
            </div>
          </div>
        </div>
        <div style="margin-top:15px;">
          <a-button type="primary" ghost class="addItem" @click="addItem">添加分账对象</a-button>
          <a-button
            v-if='functionStatus == "submit" || functionStatus == "resubmit"'
            style="margin-left: 1vw;"
            :loading="logging"
            htmlType="submit"
            type="primary"
          >提交分账名单</a-button>
          <a-button
            v-if='functionStatus == "update"'
            style="width:8vw;margin-left: 1vw;"
            :loading="logging"
            htmlType="submit"
            type="primary"
          >提交变更</a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>


<script>
import { message } from "ant-design-vue";
import api from "@/common/api";
import { mapState } from "vuex";
export default {
  name: "newReceipt",
  data() {
    return {
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 19 }
        }
      },
      henderstoken: {
        Authorization: localStorage.getItem("token"),
      },
      to:sessionStorage.getItem("memberNo") + "_" + sessionStorage.getItem("username"),
      index: Number,
      logging: false,
      receiptDetailList: [],
      memberNo: [],
      ratio: [],
      uploadList: [],
      fileList: [],
      previewVisible: false,
      previewImage: "",
      functionStatus: "", //功能状态:submit(第一次提交),resubmit(审核不过重新提交),update(修改)
      receiptList: [
        {
          memberName: "---",
          fileList: []
        }
      ],
      paySubPlanTargetRequestList: []
    };
  },
  computed: {
    ...mapState({
      imageSize: state => state.imageSize
    })
  },
  created() {},
  mounted() {
    console.log(this.$route.query.modify);
    let modifyStatus = this.$route.query.modify;
    this.functionStatus = modifyStatus
      ? modifyStatus == "resubmit"
        ? "resubmit"
        : "update"
      : "submit";

    if (modifyStatus == "resubmit") {
      //审核不通过 修改
      let id = this.$route.query.id;
      this.getsubAccountCheckDetail(id);
    } else if (modifyStatus == "update") {
      // 修改
      let id = this.$route.query.id;
      this.getsubAccountCheckDetail(id);
    }
  },
  activated() {},
  watch: {},
  methods: {
    getsubAccountCheckDetail(id) {
      let data = {
        data: id,
        page: 1,
        pageSize: 10
      };
      api.subAccountCheckDetail(
        data,
        res => {
          console.log(res);
          if (res.code == "OK") {
            this.receiptList = [];
            this.receiptDetailList = res.list;
            this.receiptDetailList.forEach((item, index) => {
              // this.receiptList[index].fileList = [];
              this.receiptList.push({
                memberName: "---",
                fileList: []
              });
              this.memberNo.push(item.targetMemberNo);
              this.ratio.push(item.percent);
              this.uploadList.push(item.protocolPath);
              let dataItem = {
                uid: index,
                name: "xxx.png",
                status: "done",
                url: "/file/file/download/" + item.protocolPath
              };
              this.receiptList[index].fileList.push(dataItem);
              this.receiptList[index].memberName = item.targetMemberName;
            });
            this.$nextTick(() => {
              //实际经营地址
              this.form.setFieldsValue({
                //对公账户
                uploadList: this.uploadList,
                memberNo: this.memberNo,
                ratio: this.ratio
              });
            });
            this.getListDivHeight();
            console.log(this.receiptDetailList);
          }
        },
        err => {}
      );
    },
    deleteItem(index) {
      if (this.receiptList.length > 1) {
        this.receiptList.splice(index, 1);
        this.getListDivHeight();
      } else {
      }
    },
    addItem() {
      let newItem = {
        memberName: "---",
        fileList: []
      };
      this.receiptList.push(newItem);
      this.getListDivHeight();
    },
    validatMemberNo(rule, value, callback) {
      const reg = new RegExp("^[0-9]{20}$");
      console.log("reg", reg);
      console.log(reg.test(value));
      if (value && !reg.test(value)) {
        callback("您输入的会员编号有误！");
        return;
      } else {
        console.log(value);
        callback();
      }
    },
    memberNoBlur(e) {
      let id = e.target.id.substring(9, 10);
      let value = e.target.value;
      let memberNo = sessionStorage.getItem("memberNo");
      if (memberNo == value) {
        this.$message.warning("请勿输入当前商户号！");
      } else {
        this.getMemberName(value, id);
      }
    },
    //匹配商户全称
    getMemberName(value, id) {
      let data = {
        memberNo: value
      };
      api.checkShowName(
        data,
        res => {
          console.log(res);
          if (res.code == "OK") {
            this.receiptList[id].memberName = res.data;
          } else {
            this.$message.error("查找失败！");
            this.receiptList[id].memberName = "---";
          }
        },
        err => {}
      );
    },
    validatRatio(rule, value, callback) {
      const reg = new RegExp(
        // "^[0-9]+(.[0-9]{2})?$"
        /^\d\.([1-9]{1,2}|[0-9][1-9])$|^[1-9]\d{0,1}(\.\d{1,2}){0,1}$|^100(\.0{1,2}){0,1}$/
      );
      if (value && !reg.test(value)) {
        callback("请输入正确的比例！");
        return;
      } else {
        console.log(value);
        callback();
      }
    },

    Submit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          this.paySubPlanTargetRequestList = [];
          let memberNoList = values.memberNo;
          let ratioList = values.ratio;
          let uploadList = values.uploadList;
          let compareList = new Set(memberNoList);

          if (compareList.size != memberNoList.length) {
            this.$message.warning("会员编号或商户名重复！");
            return false;
          }
          if (ratioList.length > 0) {
            var sum = 0;
            console.log(ratioList.length);
            for (let i = 0; i < ratioList.length; i++) {
              sum = sum + parseFloat(ratioList[i]);
              console.log(parseFloat(ratioList[i]));
            }
            if (sum > 100) {
              this.$message.warning("分账比例不能超过100%！");
              return false;
            }
          }
          console.log("memberNoList", memberNoList);
          if (memberNoList.length > 0) {
            for (let i = 0; i < memberNoList.length; i++) {
              let data = {
                targetMemberNo: "",
                targetMemberName: "",
                percent: "",
                protocolPath: ""
              };
              this.paySubPlanTargetRequestList.push(data);
            }
          }
          this.receiptList.forEach((item, index) => {
            if (item.memberName == "---") {
              this.$message.warning("商户全称有误！");
              return false;
            } else {
              this.paySubPlanTargetRequestList[index].targetMemberName =
                item.memberName;
            }
          });
          memberNoList.forEach((item, index) => {
            this.paySubPlanTargetRequestList[index].targetMemberNo = item;
          });
          ratioList.forEach((item, index) => {
            this.paySubPlanTargetRequestList[index].percent = parseFloat(item);
          });
          uploadList.forEach((item, index) => {
            this.paySubPlanTargetRequestList[index].protocolPath =
              typeof item == "object"
                ? item.fileList[0]
                  ? item.fileList[0].response.data
                  : ""
                : item
                ? item
                : "";
          });
          console.log(this.paySubPlanTargetRequestList);
          let data = {
            paySubPlanRequest: {
              functionStatus: this.functionStatus
            },
            paySubPlanTargetRequestList: this.paySubPlanTargetRequestList
          };
          this.logging = true;
          api.submitSubAccount(
            data,
            res => {
              if (res.code == "OK") {
                this.$message.success(res.message);
                this.$router.push("/listStatusQuery");
                this.logging = false;
              } else {
                this.$message.error(res.message);
                this.logging = false;
              }
            },
            err => {}
          );
        }
      });
    },
    clickUpload(index) {
      this.index = index;
      console.log(" this.index", this.index);
    },
    handlePreview(file) {
      console.log("file", file);
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handleChange({ file, fileList }) {
      let index = this.index;
      this.receiptList[index].fileList = [];
      let pos = file.name.lastIndexOf(".");
      let lastName = file.name.substring(pos, file.name.length);
      let supportTypes = [".jpeg", ".png", ".jpg"]; // jpeg、 png
      if (supportTypes.indexOf(lastName.toLowerCase()) <= -1) {
        this.$message.error("上传图片仅支持 jpeg、 png 2种格式！");
        return;
      }
      if (file.size / (1024 * 1024) > this.imageSize) {
        this.$message.error(`上传图片大小应小于${this.imageSize}Mb！`);
        return;
      }
      console.log("fileList", fileList);
      // let obj = fileList;
      // console.log(obj)
      // if (obj.response) {
      //     console.log(obj.response.data);
      //     let data =
      //     {
      //         uid: "-1",
      //         name: "xxx.png",
      //         status: "done",
      //         url: "/file/file/download/" + obj.response.data
      //     }
      //     this.receiptList[this.index].fileList.push(data);
      // }
      console.log("changeindex", index);
      this.receiptList[index].fileList = fileList;
      // this.receiptList[index].fileList.push(fileList[0]);
      // console.log(this.receiptList);
    },
    getListDivHeight() {
      console.log("vvvheight");
      let aaa = setTimeout(function() {
        let listDiv = document.getElementById("listDiv");
        // console.log(listDiv.offsetHeight);
        // console.log(listDiv.clientHeight);
        let H = ((document.body.clientHeight * 100) / 10000) * 65;
        // console.log(H)
        if (listDiv.offsetHeight > H) {
          listDiv.style.height = "65vh";
        }
      }, 10);
    }
  }
};
</script>

<style scoped>
.content {
  padding: 40px;
}

.list_item {
  padding: 20px;
  /* background: #eee; */
  /* margin-bottom: 10px; */
  border: 1px solid #eee;
  /* border-bottom: none; */
}

#listDiv {
  overflow-y: auto;
}

/*滚动条样式*/
#listDiv::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 4px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 4px;
}

#listDiv::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(0, 0, 0, 0.2);
}

#listDiv::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}

.listDiv:nth-child(even) {
  background: #eee;
}



.action {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 15vh;
}
</style>